package org.apache.commons.graph.algorithms.coloring.internal

/**
 *
 *
 * @param <V>
</V> */
internal class UncoloredOrderedVertices<V> : Comparator<Int>, Iterable<V> {

    private val orderedVertices: MutableMap<Int, MutableSet<V>> = sortedMapOf(this)

    fun addVertexDegree(v: V, degree: Int) {
        var vertices = orderedVertices[degree]

        if (vertices == null) {
            vertices = HashSet()
        }

        vertices.add(v)
        orderedVertices[degree] = vertices
    }

    /**
     * {@inheritDoc}
     */
    override fun compare(o1: Int, o2: Int): Int {
        return o2.compareTo(o1)
    }

    override fun iterator(): MutableIterator<V> {
        return object : MutableIterator<V> {
            private val keys: Iterator<Int> = orderedVertices.keys.iterator()

            private var pending: MutableIterator<V>? = null

            private var next: V? = null

            override fun hasNext(): Boolean {
                if (next != null) {
                    return true
                }

                while ((pending == null) || !pending!!.hasNext()) {
                    if (!keys.hasNext()) {
                        return false
                    }
                    pending = orderedVertices[keys.next()]!!.iterator()
                }

                next = pending!!.next()
                return true
            }

            override fun next(): V {
                if (!hasNext()) {
                    throw NoSuchElementException()
                }
                val returned = next
                next = null
                return returned!!
            }

            override fun remove() {
                pending!!.remove()
            }
        }
    }

    /**
     * Returns the number of vertices degrees in the graph.
     *
     * @return the number of vertices degrees in the graph.
     */
    fun size(): Int {
        return orderedVertices.size
    }
}